//
//  DCAlipayModule.m
//  LibWeexDCAlipay
//
//  Created by yanyu on 2019/5/14.
//  Copyright © 2019 yanyu. All rights reserved.
//

#import "DCAlipayModule.h"
#import <AFAuthSDK/AFAuthSDK.h>

@interface DCAlipayModule()
@property (nonatomic, strong) WXModuleKeepAliveCallback callback;
@end
@implementation DCAlipayModule

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(login:callback:))

- (instancetype)init{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleLogin:) name:@"AliplySSO" object:nil];
    }
    return self;
}


#pragma mark - Export Method

- (void)login:(NSDictionary *)options callback:(WXModuleKeepAliveCallback)callback
{
    
    _callback = callback;
    //你在info中/或plist中设置的appScheme
    NSString *appScheme = @"dcalipay";
    //authStr参数后台获取！和开发中心配置的app有关系，包含appid\name等等信息。
    NSString *authStr = @"app_name=mc&auth_type=AUTHACCOUNT&apiname=com.alipay.account.auth&biz_type=openservice&product_id=APP_FAST_LOGIN&scope=kuaijie&pid=2088431933057562&target_id=9b22bb0a6b874cd3855cef14234760af&app_id=2019040563762608&sign_type=RSA2&methodname=alipay.open.auth.sdk.code.get&sign=ZgkgcIZmbKPwDG9IfAZTvfhhNDGFpkMScCQX%2BN31Sx49eWklcj4%2FPRiA3CXMWHE6D2ImBmAN2H2LFficFesc47t0DtcwkW4ndXSmJWBiSgnruPgGas%2FijSkRmxvEcVRPDpbzL%2Fst8fv%2B%2FossOc1vaL7LV713rN3F4Hbl2GtJe6SlOuahSOK9MaXkSzFdYTCKhRrxiYVmPghIOyoUQgYqMx6tkNETcE0PwA%2BITjbLHdCaRSbuLvidb8ubQr90nFB78ukQ6Eqcf23iIR0d0Ir6nlY7CL3MP3laRhdWJetxY1pGQu618wkSlkS59grTQ0Gz2uLQNEchRm8sxAunv5wQqg%3D%3D";
    if (options && [options objectForKey:@"authinfo"]) {
        authStr = [options objectForKey:@"authinfo"];
    }
    //没有安装支付宝客户端的跳到网页授权时会在这个方法里回调
    [[AFAuthSDK defaultService] authv2WithInfo:authStr fromScheme:appScheme callback:^(NSDictionary *result) {
        // 解析 auth code
        NSString *resultString = result[@"result"];
        NSString *authCode = nil;
        if (resultString.length>0) {
            NSArray *resultArr = [resultString componentsSeparatedByString:@"&"];
            for (NSString *subResult in resultArr) {
                if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                    authCode = [subResult substringFromIndex:10];
                    break;
                }
            }
        }
        
        NSLog(@"执行");
        if (callback) {
            callback(result,TRUE);
        }
        NSLog(@"resultString = %@",resultString);
        //        NSLog(@"authv2WithInfo授权结果 authCode = %@", authCode?:@"");
    }];
     
   
    
}

- (void)handleLogin:(NSNotification*)noti{
    if(_callback){
        _callback(noti.object,TRUE);
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
